package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DeviceType;
import com.inter.entity.interentity.devicetype.request.RequestDeviceType;
import com.inter.entity.interentity.devicetype.request.RequestDeviceTypeData;
import com.inter.entity.interentity.devicetype.response.ResponseDeviceType;
import com.inter.entity.interentity.devicetype.response.ResponseDeviceTypeData;
import com.inter.entity.interentity.devicetype.response.ResponseDeviceTypeTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.service.DeviceTypeService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Demo 微信用户绑定，普通用户就不用绑定了，但是还是要入库
 *
 * @author lm
 * @date 2016/09/06
 */
@RestController
@Api(description = "Get device type value")
public class SelectDeviceTypeController {
    private static Logger logger = Logger.getLogger(SelectDeviceTypeController.class);

    @Autowired
    private DeviceTypeService deviceTypeService;
    @Autowired
    HttpSession session;
    @Autowired
    SequenceService sequenceService;

    @CrossOrigin
    @RequestMapping(value = "/selectdeviceType", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "Get device type", response = ResponseDeviceType.class)
    public String selectDeviceType(@ApiParam @RequestBody RequestDeviceType requestDeviceType) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        String requestStr = JSON.toJSONString(requestDeviceType);
        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestDeviceType requestPackage = JSONArray.parseObject(requestStr, RequestDeviceType.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestDeviceTypeData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    //lang为空或者为null时，默认为cn
                    if (StringUtils.isBlank(partnerCode) ||StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType)|| StringUtils.isBlank(lang)) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        logger.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            logger.info("签名验证失败！");
                            jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                            return jsonString;
                        } else {
                            //签名验证通过,代码在此处添加,下面都是为了准备response的参数
                            //取出数据从数据库
                            List<ResponseDeviceTypeTradeData> tradeData = new ArrayList<ResponseDeviceTypeTradeData>();
                            ResponseDeviceTypeTradeData tra = null;

                            List<DeviceType> typeList = deviceTypeService.queryDeviceTypeList();
                            if (typeList == null || typeList.size() <= 0) {
                                logger.info("未取到typeList数据：" + typeList);
                            } else {
                                //取到值了
                                for (DeviceType deviceType : typeList) {

                                    String deviceTypeText = deviceType.getDeviceTypeText();
                                    String deviceTypeTextEN = deviceType.getDeviceTypeTextEN();
                                    String deviceTypeValue = deviceType.getDeviceTypeValue();
                                    tra = new ResponseDeviceTypeTradeData();
                                    if (lang.equals("cn")) {
                                        tra.setDeviceTypeText(deviceTypeText);
                                    } else {
                                        tra.setDeviceTypeText(deviceTypeTextEN);
                                    }
                                    tra.setDeviceTypeValue(deviceTypeValue);
                                    tradeData.add(tra);
                                }
                                ResponseDeviceTypeData data = new ResponseDeviceTypeData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(curtime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("成功");
                                data.setTradeData(tradeData);

                                ResponseDeviceType responseDeviceType = new ResponseDeviceType();
                                responseDeviceType.setData(data);
                                responseDeviceType.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(responseDeviceType);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;
                            }

                        }
                    }
                }
            }
        }
        return null;
    }
}
